package friot.service.cloud.config.rabbitmq;

import friot.model.iot.entity.IotModel;
import friot.service.cloud.mapper.ContactProductModelMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;
import java.util.List;

import static friot.utils.constants.RedisConstants.CLOUD_DEVICE_MODEL;

/**
 * @author He Kuntao
 * @desc 模型绑定Fanout交换机配置
 * @date 2024/3/23 20:44
 */
@Slf4j
@Configuration
public class ModelBindFanoutConfig {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private ContactProductModelMapper contactProductModelMapper;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "modelBind.queue"),
            exchange = @Exchange(name = "amq.fanout", type = ExchangeTypes.FANOUT)
    ))
    public void modelBindFanout(Integer productId) {
        log.info("异步读取模型数据到Redis...productId={}", productId);
        // 存入模型到Redis
        List<IotModel> models = contactProductModelMapper.listBindModels(productId);
        for (IotModel model : models) {
            stringRedisTemplate.opsForSet()
                    .add(CLOUD_DEVICE_MODEL + productId, model.getIdentified());
        }
        log.info("异步模型绑定完成!");
    }
}
